<template>
  <div>
    <el-upload :http-request="customUpload" :on-preview="handlePreview" :on-remove="handleRemove"
      :on-change="handleChange" :file-list="fileList" list-type="picture" :before-upload="beforeUploadDealImg"
      accept=".jpeg,.jpg,.gif,.png" :limit="limitCountImg" drag>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传jpg / jpeg / gif / png文件，且不超过5MB</div>
    </el-upload>
    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { policy} from "@/api/policy.js";
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [
        {
          name: this.url.split('/')[this.url.split('/').length - 1],
          url: this.url,
        }
      ],
      disableBtn: false,
    };
  },
  props: {
    limitCountImg: {
      type: Number,
      default: 1,
    },
    url: {
      type: String,
    },
  },
  methods: {
    handlePreview(file) {

      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      console.log('remove', file, fileList);
      this.disableBtn = fileList.length >= this.limitCountImg;
      file.url = '';
      this.$emit('upload-logo', file.url);
    },
    handleChange(file, fileList) {
      console.log('change', file, fileList);
      this.fileList = fileList;
      this.disableBtn = fileList.length >= this.limitCountImg;
    },
    //获取当前日期函数
    getNowFormatDate() {
      // 获取当前时间的时间戳
      const timestamp = Date.now();

      // 将时间戳转换为Date对象
      const date = new Date(timestamp);

      // 获取年、月、日、时、分、秒，并格式化为两位数
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      const millisenconds = String(date.getMilliseconds()).padStart(3, '0');

      // 拼接成 yyyymmddhhmmss 格式
      return `${year}${month}${day}${hours}${minutes}${seconds}${millisenconds}`;
    },
    customUpload(option) {
      let file = option.file;
      const bucketName = 'images';
      let suffix = file.name.split('.').pop();
      let fileName = this.getNowFormatDate() + '.' + suffix;
      if (!['jpg', 'jpeg', 'png', 'gif'].includes(suffix)) {
        this.$message.error('只允许上传图片文件');
        option.onError(new Error('只允许上传图片文件'));
        return;
      }
      //文件大小检验
      if (file.size > 1024 * 1024 * 5) {
        this.$message.error('文件大小不能超过5MB');
        option.onError(new Error('文件大小不能超过5MB'));
        return;
      }

      policy({ bucketName, fileName })
        .then(data => {
          if (data.code === 0) {
            const uploadPutUrl = data.data;
            file.url = data.data.split('?')[0];
            this.$emit('upload-logo', file.url);
            axios.put(uploadPutUrl, file, {
              headers: {
                'Content-Type': file.type,
              }
            }).then(() => {
              option.onSuccess(data, file);
            }).catch((error) => {
              option.onError(error);
            });
          } else {
            option.onError(new Error('获取签名失败'));
          }
        })
        .catch(error => {
          option.onError(error);
        });
    }
  }
};
</script>

<style>
/* .uoloadSty .el-upload--picture-card {
  width: 110px;
  height: 110px;
  line-height: 110px;
} */
/* 上传按钮隐藏 */
/* .disUoloadSty .el-upload--picture-card {
  display: none;
} */
</style>
